<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入企业名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['platform:enterpriseInfo:add']">添加</el-button>
          </el-col>
          <!--<el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['platform:enterpriseInfo:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['platform:enterpriseInfo:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['platform:enterpriseInfo:export']">导出</el-button>
          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="enterpriseInfoList" @selection-change="handleSelectionChange">
        <el-table-column label="企业名称" align="center" prop="name">
          <template #default="scope">
            <el-tooltip class="box-item" effect="dark" content="详情" placement="top-start">
                <span style="color: #409EFF;cursor: pointer;margin-right: 5px;" @click="handleInfo(scope.row)">{{ scope.row.name
                }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="企业代码" align="center" prop="code" />
        <el-table-column label="法人微信号" align="center" prop="legalPersonaWechat" />
        <el-table-column label="法人名称" align="center" prop="legalPersonaName" />
        <el-table-column label="手机号码" align="center" prop="phone" />
        <el-table-column label="小程序数量" align="center" prop="miniProgram" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
     <!--   <el-table-column label="企业代码类型" align="center" prop="codeType" />
        <el-table-column label="是否授权" align="center" prop="authorize" />
        <el-table-column label="企业logo" align="center" prop="logo" />
        <el-table-column label="营业执照" align="center" prop="certificateOfBusiness" />
        <el-table-column label="备注" align="center" prop="remark" />-->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="管理" placement="top">
              <el-button link type="primary"  @click="handleManage(scope.row)" v-hasPermi="['platform:enterpriseInfo:manage']">管理</el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary"  @click="handleUpdate(scope.row)" v-hasPermi="['platform:enterpriseInfo:edit']">修改</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary"  @click="handleDelete(scope.row)" v-hasPermi="['platform:enterpriseInfo:remove']">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改企业信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="660px" append-to-body>
      <el-form ref="enterpriseInfoFormRef" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="24" class="mb8">
          <el-col :span="18">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="form.name"  placeholder="请输入内容" :disabled="disabled" />
              <span style="font-size: 10px;">企业名需与工商部门登记信息一致；如果是“无主体名称个体工商户”则填“个体户+法人姓名”，例如“个体户张三”</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业代码类型" prop="codeType">
              <el-select v-model="form.codeType" placeholder="请选择企业代码类型" :disabled="disabled">
                <el-option v-for="dict in code_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业代码" prop="code">
              <el-input v-model="form.code" placeholder="请输入企业代码" :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法人微信号" prop="legalPersonaWechat">
              <el-input v-model="form.legalPersonaWechat" placeholder="请输入法人微信号" :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法人姓名" prop="legalPersonaName">
              <el-input v-model="form.legalPersonaName" placeholder="请输入法人名称" :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法人身份证号" prop="legalPersonaSfzh">
              <el-input v-model="form.legalPersonaSfzh" placeholder="请输入法人身份证号" :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" :disabled="disabled" />
            </el-form-item>
          </el-col>
        <!--  <el-col :span="12">
            <el-form-item label="企业logo" prop="logo">
              <el-input v-model="form.logo" placeholder="请输入企业logo" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业执照" prop="certificateOfBusiness">
              <el-input v-model="form.certificateOfBusiness" placeholder="请输入营业执照" />
            </el-form-item>
          </el-col>-->
          <el-col :span="12">
            <el-form-item label="企业logo" prop="logo">
              <image-upload v-model="form.logo" :isShowTip="false" :limit="1" :disabled="disabled"/>
              <span style="font-size: 10px;">只能上传jpg/png文件，且不超过500kb</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业执照" prop="certificateOfBusiness">
              <image-upload v-model="form.certificateOfBusiness" :isShowTip="false" :limit="1" :disabled="disabled"/>
              <span style="font-size: 10px;">只能上传jpg/png文件，且不超过500kb</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :disabled="disabled" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" v-if="!disabled"  type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EnterpriseInfo" lang="ts">
import { listEnterpriseInfo, getEnterpriseInfo, delEnterpriseInfo, addEnterpriseInfo, updateEnterpriseInfo } from '@/api/platform/enterpriseInfo';
import { EnterpriseInfoVO, EnterpriseInfoQuery, EnterpriseInfoForm } from '@/api/platform/enterpriseInfo/types';
import { useRouter } from 'vue-router'

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const enterpriseInfoList = ref<EnterpriseInfoVO[]>([]);
const buttonLoading = ref(false);
const router = useRouter()
const loading = ref(true);
const showSearch = ref(true);
const disabled = ref(false);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const {  code_type } =
  toRefs<any>(proxy?.useDict( 'code_type'));
const queryFormRef = ref<ElFormInstance>();
const enterpriseInfoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: EnterpriseInfoForm = {
  id: undefined,
  name: undefined,
  code: undefined,
  codeType: undefined,
  authorize: undefined,
  legalPersonaWechat: undefined,
  legalPersonaName: undefined,
  legalPersonaSfzh:undefined,
  phone: undefined,
  logo: undefined,
  certificateOfBusiness: undefined,
  miniProgram: undefined,
  remark: undefined
}
const data = reactive<PageData<EnterpriseInfoForm, EnterpriseInfoQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    code: undefined,
    codeType: undefined,
    authorize: undefined,
    legalPersonaWechat: undefined,
    legalPersonaName: undefined,
    legalPersonaSfzh:undefined,
    phone: undefined,
    logo: undefined,
    certificateOfBusiness: undefined,
    miniProgram: undefined,
    params: {
    }
  },
  rules: {
    name: [
      { required: true, message: "企业名称不能为空", trigger: "blur" }
    ],
    code: [
      { required: true, message: "企业代码不能为空", trigger: "blur" }
    ],
    codeType: [
      { required: true, message: "企业代码类型不能为空", trigger: "change" }
    ],
    authorize: [
      { required: true, message: "是否授权不能为空", trigger: "blur" }
    ],
    legalPersonaWechat: [
      { required: true, message: "法人微信号不能为空", trigger: "blur" }
    ],
    legalPersonaName: [
      { required: true, message: "法人名称不能为空", trigger: "blur" }
    ],
    legalPersonaSfzh: [
      { required: true, message: "法人身份证号不能为空", trigger: "blur" }
    ],
    phone: [
      { required: true, message: "手机号码不能为空", trigger: "blur" }
    ],
    logo: [
      { required: true, message: "企业logo不能为空", trigger: "blur" }
    ],
    certificateOfBusiness: [
      { required: true, message: "营业执照不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询企业信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listEnterpriseInfo(queryParams.value);
  enterpriseInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  enterpriseInfoFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: EnterpriseInfoVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  disabled.value=false;
  dialog.visible = true;
  dialog.title = "添加企业信息";
}

/** 详情按钮操作 */
const handleInfo = async (row?: EnterpriseInfoVO) => {
  const _id = row?.id || ids.value[0]
  const res = await getEnterpriseInfo(_id);
  Object.assign(form.value, res.data);
  disabled.value=true;
  dialog.visible = true;
  dialog.title = "企业信息详情";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: EnterpriseInfoVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getEnterpriseInfo(_id);
  Object.assign(form.value, res.data);
  disabled.value=false;
  dialog.visible = true;
  dialog.title = "修改企业信息";
}

/** 商家管理操作 */
const handleManage = async (row?: EnterpriseInfoVO) => {
  const _id = row?.id || ids.value[0]
  router.push({path:'/merchant/manageConfig',query:{id:_id}})
}

/** 提交按钮 */
const submitForm = () => {
  enterpriseInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateEnterpriseInfo(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addEnterpriseInfo(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: EnterpriseInfoVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除企业信息编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delEnterpriseInfo(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('platform/enterpriseInfo/export', {
    ...queryParams.value
  }, `enterpriseInfo_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
